/**
 * 增强欢迎语
 * 在企业微信发送欢迎语之后，补充额外的欢迎语内容
 *
 * 运行方式：
 * 设置对`企业微信欢迎语`的匹配规则，当检测到的`企业微信欢迎语`符合规则时，就发送额外的欢迎语。
 */
import type { OptionalFields } from '@gnlab/utils'
import { getLogger, Service } from '@gnlab/utils'
import type { Services } from '@/services'
import { API } from '@/services/common/api'
import { type Word, formatIrregularWord } from '@/services/common/definition'

const logger = getLogger('services/features/welcomeMessage')

// 要匹配的企业微信欢迎语类型
export enum WelcomeMessageMatchType {
  Text = 0,
  MiniProgram = 1,
  Image = 2,
  Video = 3,
}

export interface BaseWelcomeMessage {
  name: string // 欢迎语名称
  matchType: WelcomeMessageMatchType // 要匹配的`企业微信欢迎语`类型
  keyword: string | null // matchType=Text 时有值，要匹配的关键词
  appid: string | null // matchType=MiniProgram 时有值，匹配的小程序 appid 及 enterpoint
  enterpoint: string | null
  words: Word[] // 要发送的欢迎语内容
  enable: boolean // 此条规则是否启用
}

export interface WelcomeMessage extends BaseWelcomeMessage {
  id: number // 欢迎语 ID
}

export function getEmptyWelcomeMessage(): BaseWelcomeMessage {
  return {
    name: '',
    matchType: WelcomeMessageMatchType.Text,
    keyword: '',
    appid: null,
    enterpoint: null,
    words: [],
    enable: true,
  }
}

interface RawWelcomeMessage {
  Id: number
  Name: string
  MsgType: WelcomeMessageMatchType
  Keyword: string | null
  AppId: string | null
  EnterPoint: string | null
  Content: string | null
  Enable: boolean
}
function formatRawWelcomeMessage(raw: RawWelcomeMessage): WelcomeMessage {
  let words: Word[]
  try {
    words = (JSON.parse(raw.Content ?? '[]') as Word[]).map(formatIrregularWord)
  } catch (e) {
    words = []
    logger.warn('解析话术内容失败', raw)
  }
  return {
    id: raw.Id,
    name: raw.Name,
    matchType: raw.MsgType,
    keyword: raw.Keyword,
    appid: raw.AppId,
    enterpoint: raw.EnterPoint,
    words,
    enable: raw.Enable,
  }
}
function formatWelcomeMessageToSubmit(
  data: OptionalFields<WelcomeMessage, 'id'>,
): OptionalFields<RawWelcomeMessage, 'Id'> {
  return {
    Id: data.id,
    Name: data.name,
    MsgType: data.matchType,
    Keyword: data.keyword,
    AppId: data.appid,
    EnterPoint: data.enterpoint,
    Content: JSON.stringify(data.words),
    Enable: data.enable,
  }
}

export class WelcomeMessages extends Service<Services> {
  async load() {
    return API('/Config/GetWelcomeMessage', {
      formatter(data: RawWelcomeMessage[] | null) {
        return (data ?? []).map(formatRawWelcomeMessage)
      },
    })
  }

  async addOrUpdate(data: OptionalFields<WelcomeMessage, 'id'>) {
    return API('/Config/SaveWelcomeMessage', {
      data: formatWelcomeMessageToSubmit(data),
    })
  }

  async remove(id: number) {
    return API('/Config/RemoveWelcomeMessage', {
      data: { id },
    })
  }
}
